/*
 * Copyright (c) 2021
 * User:魔金多商户商城
 * File:HttpUtils.java
 * Date:2020/09/13 08:43:13
 */

package com.ruoyi.common.utils.http;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.*;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;

/**
 * 通用http发送方法
 *
 * @author ruoyi
 */
public class HttpUtils {
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        return sendGet(url, param, Constants.UTF8);
    }

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url         发送请求的 URL
     * @param param       请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @param contentType 编码类型
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param, String contentType) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            log.info("sendGet - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjQ5OTksInNjb3BlIjo4LCJleHAiOjE2MTg3OTU5OTYsImlhdCI6MTYxODcyMzk5Nn0.IvxTup39DU9YIzRefPYfj8uwrkovO5uEqiIQBvScKE4");
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            String urlNameString = url;
            log.info("sendPost - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }

    public static String sendSSLPost(String url, String param) {
        StringBuilder result = new StringBuilder();
        String urlNameString = url + "?" + param;
        try {
            log.info("sendSSLPost - {}", urlNameString);
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
            URL console = new URL(urlNameString);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String ret = "";
            while ((ret = br.readLine()) != null) {
                if (ret != null && !"".equals(ret.trim())) {
                    result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
                }
            }
            log.info("recv - {}", result);
            conn.disconnect();
            br.close();
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
        }
        return result.toString();
    }

    public static void main(String[] args) {
        String s = HttpUtils.sendPost("https://developer.toutiao.com/api/apps/jscode2session", String.format("appid=%s&secret=%s&code=%s&grant_type=authorization_code", "tt32884435adb0b8c701",
                "c88c04453281b8df7180ac019e7a442b518f2f96 ", "YNz4dufi-Qk-0vPQjF0GHlQp4k3ed1W7zbo5sjhP08q8EVb-oTZ31LbxlBRr1mCHiAGRGuLoKBnklAZwXe7QCqkYU2txHSfVMESG_Ux2LBf3pnKI05HPCTFdmlY"));
        System.out.println(JSONObject.parseObject(s));
        String url = "http://apiv3.yangkeduo.com/operation/14/groups";
        String rspStr = HttpUtils.sendGet(url, "page=1&size=100&opt_type=1");
        JSONObject obj = JSONObject.parseObject(rspStr);
        JSONArray region = obj.getJSONArray("goods_list");
        // {"goods_name":"本命牛年衣服2021红色新年卫衣暴富情侣装拜年服加绒加厚女男冬季","thumb_url":"http://t00img.yangkeduo.com/goods/images/2021-01-11/55cc05fda3c2eb92108c2649af85aad5.jpeg",
        // "hd_thumb_wm":"","country":"","sales_tip":"已拼6381件","icon":{"width":"133","id":"20013","tag_series":"2",
        // "url":"https://commimg.pddpic.com/oms_img_ng/2021-01-28/642e4467-c0c0-4986-b8a6-9b5290a7f6e3.png","height":"45"},
        // "cnt":6381,"goods_id":215360622164,"hd_thumb_url":"http://t00img.yangkeduo.com/goods/images/2021-01-11/3b53f9e86cac830d6fb5b9a9eac8094f.jpeg",
        // "event_type":0,"normal_price":5290,"p_rec":{"sec_info":"3D9F27CB3016FA3365666E0B6F1160F0","list_id":"fenlei_gyl_818027987__14","bk":"75","vid":"djAuMC4y4oeoMjQ0OTM1ODc4MDY0MDkzNDIwOA==","experiment":"{\"4033\":{\"g\":\"4033_0User\",\"bk\":\"30\"},\"4079\":{\"g\":\"4079_0User\",\"bk\":\"17\"},\"4112\":{\"g\":\"4112_0User\",\"bk\":\"68\"},\"3361\":{\"g\":\"3361_0User\",\"bk\":\"96\"},\"4092\":{\"g\":\"4092_0User\",\"bk\":\"66\"},\"3184\":{\"g\":\"3184_0User\",\"bk\":\"71\"},\"3261\":{\"g\":\"3261_0_base\",\"bk\":\"11\"},\"3260\":{\"g\":\"3260_V3\",\"bk\":\"33\"},\"3614\":{\"g\":\"3614_defaultGroup\",\"bk\":\"10\"},\"3818\":{\"g\":\"3818_0User\",\"bk\":\"61\"},\"3157\":{\"g\":\"3157_expGroup\",\"bk\":\"26\"},\"3891\":{\"g\":\"3891_0User\",\"bk\":\"48\"},\"3156\":{\"g\":\"3156_0User\",\"bk\":\"90\"},\"3232\":{\"g\":\"3232_0User\",\"bk\":\"50\"},\"3472\":{\"g\":\"3472_user0\",\"bk\":\"90\"},\"3151\":{\"g\":\"3151_0User\",\"bk\":\"78\"},\"3150\":{\"g\":\"3150_0User\",\"bk\":\"43\"},\"3270\":{\"g\":\"3270_0_base\",\"bk\":\"37\"},\"0\":{\"g\":\"DEFAULT\",\"bk\":\"19\"},\"3548\":{\"g\":\"3548_0User\",\"bk\":\"97\"},\"3522\":{\"g\":\"3522_0_base\",\"bk\":\"9\"},\"3267\":{\"g\":\"3267_0User\",\"bk\":\"6\"},\"3465\":{\"g\":\"3465_0User\",\"bk\":\"75\"},\"3487\":{\"g\":\"3487_0User\",\"bk\":\"94\"},\"3702\":{\"g\":\"3702_0User\",\"bk\":\"89\"},\"3209\":{\"g\":\"3209_0User\",\"bk\":\"52\"},\"3967\":{\"g\":\"3967_0User\",\"bk\":\"66\"},\"3528\":{\"g\":\"3528_unused\",\"bk\":\"78\"}}","pvid":"3e94548f-f7c6-4f23-941e-eb6084d858f21612587680041","price":"5090.0","zyw":"false","owner":"scene","set":"shb1","org":"rec","sceneName":"fenlei","g":"carrier","goods_id":"215360622164","opt1":"14","m":"8B32CC8C9F0AC2114B788FB092B3C6A0","opt_id":"14","app_name":"fenlei_gyl","te":"1612587680195","t":"70A63CC217483AF0D0700F500CCF595C","stage":"1","rpd_scene":"index_opt","request_id":"5186cda1-e474-45db-853c-223ec717f145","ab_id":"ZvEZbmAR","ts":"1612587680038"},"tag_list":[{"text":"立减2元","text_color":"#E02E24","type":4047,"tag_track_info":"4&null"}],"link_url":"goods.html?goods_id=215360622164","market_price":8880,"image_wm":"","short_name":"本命牛年衣服2021红色新年卫衣暴富情侣装拜年服加绒加厚女男冬季","thumb_wm":"","tag":-1,"group":{"price":5090,"customer_num":2}}
        for (int i = 0; i < region.size(); i++) {
            System.out.println(region.getJSONObject(i));
            //System.out.println(region.getJSONObject(i).get("goods_name"));

        }

    }

    private static class TrustAnyTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }
}